<template>
  <div class="testDetail">
    <div class="testRecord" v-if="formData">
      <div class="header">
        <h3>{{ name }}</h3>
        <!-- <span>总分:{{ score }} </span> -->
        &nbsp;
        <span> 总时长: {{ time }}</span>
      </div>
      <div class="body">
        <template v-for="(answerItem, index) in answer.answerItems">
          <div :key="index">
            <span class="title" v-if="answerItem.type == 0">选择题:</span>
            <span class="title" v-else-if="answerItem.type == 1">判断题:</span>
            <span class="title" v-else-if="answerItem.type == 2">编程题:</span>
            <span :key="index" v-for="(item, index) in answerItem.items">
              <el-tag
                :class="questionCompleted(item.completed)"
                class="testTitltTag"
                @click="
                  goAnchor('#question-' + item.questionId, answerItem.type)
                "
              >
                {{ item.itemOrder }}
              </el-tag>
            </span>
          </div>
        </template>
      </div>
      <div class="footer">
        <h4>剩余时间：</h4>
        <span class="testRemainTime">{{ formatSeconds }}</span>
        <el-button
          class="submit"
          type="primary"
          round
          icon="el-icon-finished"
          @click="submitPaper"
          >提交试卷</el-button
        >
      </div>
    </div>
    <div class="mainContent">
      <el-form ref="form" label-width="100px" v-if="formData.type != 2">
        <el-row>
          <el-button
            class="btn_back"
            type="primary"
            plain
            icon="el-icon-d-arrow-left"
            @click="back"
            >返回</el-button
          >
          <h3 v-if="formData.type == 0">选择题</h3>
          <h3 v-if="formData.type == 1">判断题</h3>

          <el-card
            class="test-item-box"
            v-if="
              formData.questions !== undefined &&
                formData.questions.length > 0 &&
                formData.type != 2
            "
          >
            <el-form-item
              :key="index"
              :label="index + 1 + '.'"
              v-for="(questionItem, index) in formData.questions"
              class="exam-question-item"
              label-width="50px"
              :id="'question-' + questionItem.id"
            >
              <div style="text-align:left">
                <span style="padding-right: 10px;">{{
                  questionItem.title
                }}</span>
              </div>
              <div style="text-align:left;padding-left: 20px;">
                <el-radio-group
                  v-model="
                    answer.answerItems[formData.type].items[index].content
                  "
                  @change="
                    answer.answerItems[formData.type].items[
                      index
                    ].completed = true;
                    storeAnswer();
                  "
                >
                  <el-radio
                    v-for="item in questionItem.answers"
                    :key="item.prefix"
                    :label="item.prefix"
                  >
                    {{ item.prefix + ".   " + item.content }}
                  </el-radio>
                </el-radio-group>
              </div>
              <span style="padding-left: 10px;"></span>
            </el-form-item>
          </el-card>
        </el-row>
        <el-button
          v-if="formData.type != 2"
          icon="el-icon-d-arrow-right"
          type="primary"
          @click="nextForm"
        >
          下一页
        </el-button>
      </el-form>
      <el-form
        ref="form"
        label-width="100px"
        v-if="formData.type == 2 && !programDetailsShow"
      >
        <el-row>
          <el-button
            class="btn_back"
            type="primary"
            plain
            icon="el-icon-d-arrow-left"
            @click="back"
            >返回</el-button
          >
          <h3>编程题</h3>
          <el-card v-if="formData.type == 2 && !programDetailsShow">
            <el-table
              size="mini"
              :data="formData.questions"
              border
              fit
              stripe
              highlight-current-row
              width="100%"
              @row-dblclick="rowDblclick"
            >
              <el-table-column
                v-for="(item, index) of columnList"
                :key="index"
                :width="item.width"
                align="center"
                :label="item.label"
              >
                <template v-slot="{ row }">
                  <span v-if="item.prop == 'list'" @click="answer(row.index)">
                    <el-button
                      v-if="row.answer != null && row.answer == false"
                      type="info"
                      round
                      size="small"
                      icon="el-icon-view"
                      >查看</el-button
                    >
                    <el-button
                      v-else-if="row.answer != null && row.answer == true"
                      type="primary"
                      round
                      size="small"
                      icon="el-icon-view"
                      >查看</el-button
                    >
                    <span v-else>无</span>
                  </span>
                  <span
                    v-else-if="item.prop == 'answer' && row[item.prop] != null"
                  >
                    <i v-if="row[item.prop]" class="el-icon-success"></i>
                    <i v-else class="el-icon-error"></i>
                  </span>
                  <span
                    v-else-if="item.prop == 'name'"
                    class="enter"
                    @click="enter(row.index)"
                  >
                    {{ row[item.prop] }}
                  </span>
                  <span v-else>{{ row[item.prop] }}</span>
                </template>
              </el-table-column>
              <el-table-column width="0" align="center" label="状态">
                <template v-slot="{ row }">
                  <span>{{ statusInfo["" + row.id] }}</span>
                </template>
              </el-table-column>
              <el-table-column width="0" align="center" label="操作">
                <template v-slot="{ row }">
                  <span class="enter el-icon-edit-outline" @click="enter(row)"
                    >&nbsp;进入</span
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-row>
      </el-form>
      <div class="program_details" v-if="programDetailsShow">
        <!-- 路由视图 -->
        <router-view @submitSrc="srcAnswer" @back="backProgram"></router-view>
      </div>
    </div>
  </div>
</template>
<script>
import {
  showPaperDetail,
  submitTask,
  storeExamAnswer,
  getExamAnswerCache,
  getExamSituation
} from "@/api/task.js";
const columnList = [
  {
    label: "题目编号",
    type: "text",
    prop: "id",
    width: 200
  },
  {
    label: "题目名称",
    type: "text",
    prop: "title",
    width: 500
  }
];

export default {
  name: "testDetail",
  data() {
    return {
      statusInfo: {},
      programDetailsShow: false,
      columnList,
      formData: {
        questions: [],
        type: 0
      }, //当前题型信息
      taskData: [], //任务信息
      resData: [], //试卷信息
      answerContent: [], //每道题的答题信息
      name: "第一单元测试",
      time: null,
      endTime: null,
      score: 100,
      remainTime: null,
      answer: {
        doTime: 0, //花费时间
        answerItems: []
      },
      user: null
    };
  },
  created() {
    this.user = JSON.parse(localStorage.getItem("user"));
    this.initData();
    this.time = parseInt(
      (new Date(this.taskData.endTime).getTime() -
        new Date(this.taskData.startTime).getTime()) /
        1000
    );
    this.time =
      parseInt(this.time / 3600) +
      "小时" +
      parseInt((this.time / 60) % 60) +
      "分钟";

    this.remainTime = parseInt(
      (new Date(this.taskData.endTime).getTime() - new Date().getTime()) / 1000
    );
    this.name = this.taskData.title;
    this.timeReduce();
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  computed: {
    formatSeconds() {
      return (
        parseInt(this.remainTime / 3600) +
        "时" +
        parseInt((this.remainTime / 60) % 60) +
        "分" +
        (this.remainTime % 60) +
        "秒"
      );
    }
  },
  methods: {
    async initCache() {
      this.taskData = this.$route.params.taskData;
      const userId = this.user.userId;
      const examId = this.taskData.id;
      const res = await getExamAnswerCache({ userId, examId });
      // this.answer.answerItems.forEach(item => {
      //   answerItems.push(item.items);
      // });
      if (res.data) {
        const array = res.data.answerContent;
        console.log(array, "cache");
        // answer.answerItems[formData.type].items[index].content
        let index = 0;
        this.answer.answerItems[0].items.forEach(item => {
          item.content = array[index++].answer;
          if (item.content != "*") {
            item.completed = true;
          }
        });
        this.answer.answerItems[1].items.forEach(item => {
          item.content = array[index++].answer;
          if (item.content != "*") {
            item.completed = true;
          }
        });
        this.answer.answerItems[2].items.forEach(item => {
          item.content = array[index++].answer;
          if (item.content != "*") {
            item.completed = true;
          }
        });
      }
      this.getStatusInfo();
    },
    async getStatusInfo() {
      const userId = this.user.userId;
      const examId = this.taskData.id;
      const res = await getExamSituation({ userId, examId });
      const info = res.data;
      info.forEach(item => {
        this.$set(this.statusInfo, "" + item.problemId, item.situationInfo);
      });
    },
    storeAnswer() {
      this.answerContent = [];
      let obj = [];
      let answerItems = [];
      this.answer.answerItems.forEach(item => {
        answerItems.push(item.items);
      });
      //console.log(answerItems);
      answerItems.forEach(items => {
        //console.log(item);
        items.forEach(item => {
          let examProblemType = "";
          let answer = "";
          let result = 0;
          if (item.type == 0) {
            //0:选择题，1:判断题， 2:程序题;
            examProblemType = 2;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          } else if (item.type == 1) {
            examProblemType = 3;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          } else {
            examProblemType = 1;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          }
          obj = {
            id: item.itemOrder,
            problemId: item.questionId,
            examProblemType: examProblemType,
            answer: answer,
            result: result,
            score: item.score
          };
          this.answerContent.push(obj);
        });
      });
      //console.log(this.answerContent);
      let postData = {
        userId: Number(this.user.userId),
        examId: Number(this.taskData.id),
        classId: this.user.classList[0].id,
        answerContent: this.answerContent
      };
      console.log(postData, "缓存内容");

      storeExamAnswer(postData).then(res => {
        console.log("缓存成功");
      });
    },
    srcAnswer(src, id) {
      console.log(src, "src");
      console.log(id, "id");
      // answer.answerItems[formData.type].items[index].content
      this.answer.answerItems[this.formData.type].items.forEach(item => {
        if (item.questionId === id) {
          item.content = src;
          item.completed = true;
        }
      });
      this.storeAnswer();
      this.getStatusInfo();
      setTimeout(this.getStatusInfo, 10000);
      setTimeout(this.getStatusInfo, 20000);
    },
    // 进入编程题详情页面
    enter(data) {
      console.log(data);
      data.examAndExperimentId = this.taskData.id;
      let taskData = this.taskData;
      console.log(taskData);
      this.$router.push({
        name: "programDetail",
        query: { id: data.id },
        params: {
          data: data,
          taskData
        }
      });
      this.programDetailsShow = true;
    },
    // 监听子组件返回事件
    backProgram() {
      this.goAnchor(this.answer.answerItems[2].items[0].itemOrder, 2);
    },
    rowDblclick(row, column, event) {
      this.enter(row.index);
    },
    //初始化数据
    async initData() {
      const loading = this.$loading({
        lock: true,
        text: "试卷初始化中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.taskData = this.$route.params.taskData;
      console.log(this.taskData, "taskData");
      let obj = {
        testPaperId: this.taskData.paperId,
        examId: this.taskData.id
      };
      await showPaperDetail(obj).then(res => {
        this.resData = res.data;
        console.log(res.data, "初始化响应数据");
        this.formData.questions = this.resData.choicesProblem;
        this.formData.type = 0;
      });
      this.initAnswer();
      loading.close();
    },
    //初始化答题卡
    initAnswer() {
      this.resData.items = [
        this.resData.choicesProblem,
        this.resData.trueOrFalse,
        this.resData.programmingQuestions
      ];
      let titleItemArray = this.resData.items;
      let index = 1;
      for (let tIndex in titleItemArray) {
        //遍历所有题目
        let questionArray = titleItemArray[tIndex]; //获取同一类型的题目
        this.answer.answerItems.push({
          type: tIndex, //0:选择题，1:判断题， 2:程序题;
          items: [] //该类型所有小题的信息
        });
        if (questionArray !== [] || questionArray != null) {
          //该类型题目不为空
          for (let qIndex in questionArray) {
            //遍历该类型所有小题
            let question = questionArray[qIndex];
            this.answer.answerItems[tIndex].items.push({
              //获取每一小题的答案信息
              questionId: question.id,
              content: null, //选择的答案
              correct: question.correct,
              completed: false,
              itemOrder: Number(index++),
              score: question.score,
              type: tIndex
            });
          }
        }
      }
      console.log(this.answer.answerItems, "初始化数据");
      this.initCache();
    },

    //考试倒计时
    timeReduce() {
      let _this = this;
      this.timer = setInterval(function() {
        if (_this.remainTime <= 0) {
          _this.submit();
          clearInterval(_this.timer);
        } else {
          --_this.remainTime;
        }
      }, 1000);
    },
    //定位到某一道题
    goAnchor(index, type) {
      console.log(index);
      type == 0
        ? (this.formData.questions = this.resData.choicesProblem)
        : type == 1
        ? (this.formData.questions = this.resData.trueOrFalse)
        : (this.formData.questions = this.resData.programmingQuestions);
      this.formData.type = type;
      console.log(this.formData, "点击后fromdata");
      //如果是编程题跳出来
      if (this.programDetailsShow) {
        //this.$router.go(-1);
        this.programDetailsShow = false;
      }
      if (type != 2) {
        this.$nextTick().then(() => {
          console.log(this.$el.querySelector(index));
          this.$el.querySelector(index).scrollIntoView({
            behavior: "instant",
            block: "center",
            inline: "nearest"
          });
        });
      } else {
        this.$el.querySelector(".mainContent").scrollIntoView();
      }
    },
    backList() {
      this.$router.go(-1);
      this.programDetailsShow = false;
    },
    questionCompleted(completed) {
      if (completed == false) return "info";
      else {
        return "success";
      }
    },

    //提交答卷
    submit() {
      //console.log(this.answer.answerItems)
      //console.log(this.answer.answerItems[this.formData.type].items[0].content);
      this.answerContent = [];
      let obj = [];
      let answerItems = [];
      this.answer.answerItems.forEach(item => {
        answerItems.push(item.items);
      });
      //console.log(answerItems);
      answerItems.forEach(items => {
        //console.log(item);
        items.forEach(item => {
          let examProblemType = "";
          let answer = "";
          let result = 0;
          if (item.type == 0) {
            //0:选择题，1:判断题， 2:程序题;
            examProblemType = 2;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          } else if (item.type == 1) {
            examProblemType = 3;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          } else {
            examProblemType = 1;
            if (!item.content) {
              item.content = "*";
            }
            answer = item.content;
          }
          // if (item.content == item.correct) {
          //   result = 1;
          // } else {
          //   result = 0;
          // }
          obj = {
            id: item.itemOrder,
            problemId: item.questionId,
            examProblemType: examProblemType,
            answer: answer,
            result: result,
            score: item.score
          };
          this.answerContent.push(obj);
        });
      });
      console.log(this.answerContent);
      //console.log(this.answerContent);
      let postData = {
        userId: Number(this.user.userId),
        examId: Number(this.taskData.id),
        classId: this.user.classList[0].id,
        answerContent: this.answerContent
      };
      console.log(postData, "提交内容");

      submitTask(postData)
        .then(res => {
          this.$message.success("提交成功！");
          // this.$router.push({
          //   path: "/main/testModule/test",
          //   params: { isSubmit: true }
          // });
          this.back();
        })
        .catch(() => {
          this.$message.error("提交失败！");
          this.back();
        });
    },

    // 主动交卷
    submitPaper() {
      this.$confirm("确定交卷吗?", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "交卷",
        cancelButtonText: "不交卷",
        type: "warning"
      })
        .then(() => {
          this.submit();
          //this.$router.push({
          //  path: "./test"
          //});
          // this.back();
        })
        .catch(err => {
          console.log(err);
        });
    },
    //返回
    back() {
      //this.$router.go(-1);
      this.$router.push({ path: "/main/testModule/test" });
    },
    //下一页
    nextForm() {
      if (this.formData.type == 2) {
        this.formData.questions = this.resData.choicesProblem;
        this.formData.type = 0;
      } else if (this.formData.type == 1) {
        this.formData.questions = this.resData.programmingQuestions;
        this.formData.type = 2;
      } else {
        this.formData.questions = this.resData.trueOrFalse;
        this.formData.type = 1;
      }
      if (this.formData.questions == null || this.formData.questions == [])
        this.nextForm();
      this.$el.querySelector(".mainContent").scrollIntoView();
      //this.programDetailsShow = false;
    }
  },
  //进出编程题题目详情判断，调整programDetailsShow，提高流畅度
  beforeRouteUpdate(to, from, next) {
    // just use `this`
    if (to.name == "testDetail") this.programDetailsShow = false;
    next();
  }
};
</script>
<style lang="scss" scoped>
.testDetail {
  width: 100%;
  min-height: 100%;
  background-color: rgb(236, 245, 255);
  padding: 30px 0px 30px 0px;
}

.testRecord {
  width: 280px;
  position: relative;
  left: 80px;
  top: 30px;
  bottom: 30px;
  background-color: white;
  position: fixed;

  .header {
    font-size: 16px;
    text-align: left;
    margin: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #dedede;
  }

  .body {
    text-align: left;
    margin: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #dedede;

    .title {
      display: block;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
      margin-top: 10px;
      color: #409eff;
    }

    .testTitltTag {
      cursor: pointer;
      text-align: center;
      width: 35px;
      margin: 0px 6px 3px;
    }
  }

  .footer {
    margin: 20px;
    text-align: left;
    font-size: 16px;

    .testRemainTime {
      margin-left: 80px;
      color: #409eff;
    }
  }
}

.testRecord .submit {
  position: absolute;
  bottom: 100px;
  left: 80px;
}

.mainContent {
  background-color: rgb(255, 255, 255);
  height: 100%;
  margin-left: 400px;
  margin-right: 80px;
}

.enter {
  cursor: pointer;
}

.enter:hover {
  color: red;
  text-decoration: underline;
}

.program_details {
  border: solid 10px white;
  position: relative;
  height: 100%;
}

.testRecord .el-tag.el-tag--light.info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

.testRecord .el-tag.el-tag--light.success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

.back {
  position: absolute;
  top: 20px;
  left: 20px;
}
.btn_back {
  position: absolute;
  right: 10px;
}
</style>
